package com.mybatis.demo.plugin;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class HWInvocationHandler implements InvocationHandler {
  /**
   * 创建代理对象方法
   */
  public static Object wrap(Object target, List<Interceptor> interceptors) {
    HWInvocationHandler targetProxy = new HWInvocationHandler(interceptors, target);
    return Proxy.newProxyInstance(target.getClass().getClassLoader(),
      target.getClass().getInterfaces(),
      targetProxy);
  }

  private List<Interceptor> interceptors = new ArrayList<>();

  //目标类
  private Object target;

  public HWInvocationHandler(List<Interceptor> interceptors, Object target) {
    this.interceptors = interceptors;
    this.target = target;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    for (Interceptor interceptor : interceptors) {
      interceptor.intercept();
    }
    Object obj = method.invoke(target, args);
    return obj;
  }
}
